import axios from 'axios'
import { useUserStore } from '../stores/user'
import router from '../router'

// 创建 axios 实例
const request = axios.create({
  baseURL: 'http://localhost:8080/elm',
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    if (userStore.isLoggedIn()) {
      config.params = { 
        ...config.params,
        userId: userStore.userId
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未登录，跳转到登录页
          router.push('/login')
          break
        case 500:
          alert('服务器错误，请稍后重试')
          break
        default:
          alert(error.response.data.message || '请求失败')
      }
    } else {
      alert('网络错误，请检查网络连接')
    }
    return Promise.reject(error)
  }
)

export default request 